﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SSRS.Core;
using SSRS.PlugIns.Base.AuthorizeModule;
using SSRS.Util;
using SSRS.Util.Operat;

namespace SSRS.Application.Web
{
    public class HandlerLoginAttribute : ActionFilterAttribute,IDependency
    {
        private DataAuthorizeIBLL dataAuthorizeIBLL { get; set; } 
        private FilterMode _customMode { get; set; }
        private FilterIPBLL filterIPBLL { get; set; }
        private FilterTimeIBLL filterTimeIBll { get; set; }
        /// <summary>默认构造</summary>
        /// <param name="Mode">认证模式</param>
        public HandlerLoginAttribute(FilterMode Mode)
        {
            _customMode = Mode;
            
            //测试嵌入
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // 登录拦截是否忽略
            if (_customMode == FilterMode.Ignore)
            {
                return;
            }

            var request = context.HttpContext.Request;
            string account = "";
            if (!request.Headers["account"].IsEmpty())
            {
                account = request.Headers["account"].ToString();
            }


            var areaName = context.RouteData.DataTokens["area"] + "/";            //获取当前区域
            var controllerName = context.RouteData.Values["controller"] + "/";    //获取控制器
            var action = context.RouteData.Values["Action"];                      //获取当前Action
            string currentUrl = "/" + areaName + controllerName + action;               //拼接构造完整url
            WebHelper.AddHttpItems("currentUrl", currentUrl);

            var _currentUrl = WebHelper.GetHttpItems("currentUrl");
            if (_currentUrl.IsEmpty())
            {
                WebHelper.AddHttpItems("currentUrl", currentUrl);
            }
            else
            {
                WebHelper.UpdateHttpItem("currentUrl", currentUrl);
            }

            // 验证登录状态
            int res = OperatorHelper.Instance.IsOnLine(account).stateCode;
            if (res != 1)// 登录过期或者未登录
            {
                if (res == 2)
                {
                    if (context.HttpContext.Request.IsAjaxRequest())
                    {
                        context.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = "other" }.ToJson() };
                    }
                    else
                    {
                        context.Result = new RedirectResult("~/Login/Index?error=other");
                    }
                    return;

                }



                if (context.HttpContext.Request.IsAjaxRequest())
                {
                    context.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = "nologin" }.ToJson() };
                }
                else
                {
                    context.Result = new RedirectResult("~/Login/Index");
                }
                return;
            }
            // IP过滤
            if (!this.FilterIP())
            {
                if (context.HttpContext.Request.IsAjaxRequest())
                {
                    context.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = "noip" }.ToJson() };
                }
                else
                {
                    context.Result = new RedirectResult("~/Login/Index?error=ip");
                }
                return;
            }
            // 时段过滤
            if (!this.FilterTime())
            {
                if (context.HttpContext.Request.IsAjaxRequest())
                {
                    context.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = "notime" }.ToJson() };
                }
                else
                {
                    context.Result = new RedirectResult("~/Login/Index?error=time");
                }
                return;
            }

            // 判断当前接口是否需要加载数据权限
            if (!this.DataAuthorize(context))
            {
                context.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.fail, info = "没有该数据权限" }.ToJson() };
                return;
            }
        }


        /// <summary>
        /// IP过滤
        /// </summary>
        /// <returns></returns>
        private bool FilterIP()
        {
            bool isFilterIP = Config.GetValue("FilterIP").ToBool();
            if (isFilterIP == true)
            {
                return filterIPBLL.FilterIP();
            }
            return true;
        }
        /// <summary>
        /// 时段过滤
        /// </summary>
        /// <returns></returns>
        private bool FilterTime()
        {
            bool isFilterIP = Config.GetValue("FilterTime").ToBool();
            if (isFilterIP == true)
            {
                return true;
            }
            return true;
        }

        private bool DataAuthorize(ActionExecutingContext filterContext)
        {
            var areaName = filterContext.RouteData.DataTokens["area"] + "/";            //获取当前区域
            var controllerName = filterContext.RouteData.Values["controller"] + "/";    //获取控制器
            var action = filterContext.RouteData.Values["Action"];                      //获取当前Action
            string currentUrl = "/" + areaName + controllerName + action;               //拼接构造完整url

            if (currentUrl.StartsWith("//Home/Index")
                || currentUrl.StartsWith("//Login/Index")
                || currentUrl.StartsWith("//Login/VerifyCode")
                || currentUrl.StartsWith("//Login/CheckLogin"))
            {
                return true;
            }



            return dataAuthorizeIBLL.SetWhereSql(currentUrl,false);
        }
    }

}
